<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :inline="true" :model="userPageParam" class="user-search">
      <el-form-item label="搜索：">
        <el-select size="small" v-model="userPageParam.status" placeholder="请选择">
          <el-option label="全部" value=""></el-option>
          <el-option label="正常" value="1"></el-option>
          <el-option label="已锁定" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-input size="small" v-model="userPageParam.userName" placeholder="输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-input size="small" v-model="userPageParam.phone" placeholder="输入手机号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
        <el-button size="small" type="primary" @click="handleDept()">部门设置</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" @selection-change="selectChange" :data="this.userPageList" highlight-current-row v-loading="loading"
              border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="50">
      </el-table-column>
      <el-table-column align="center" sortable prop="userCode" label="用户编码" width="80">
      </el-table-column>
      <el-table-column align="center" sortable prop="userName" label="用户名" width="80">
      </el-table-column>
      <el-table-column align="center" sortable prop="nickName" label="昵称" width="120">
      </el-table-column>
      <el-table-column align="center" sortable prop="phone" label="电话" width="100">
      </el-table-column>
      <el-table-column align="center" sortable prop="email" label="邮件" min-width="120">
      </el-table-column>
      <el-table-column align="center" sortable prop="statusName" label="用户状态" min-width="50">
      </el-table-column>
      <el-table-column align="center" sortable prop="createTime" label="创建时间" min-width="160">
        <template slot-scope="scope">
          <div>{{scope.row.createTime|timestampToTime}}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
          <el-button size="mini" @click="resetPassword(scope.$index, scope.row)">重置密码</el-button>
          <el-button size="mini" @click="dataAccess(scope.$index, scope.row)">数据权限</el-button>
          <el-button size="mini" @click="lockUser(scope.$index, scope.row)">锁定</el-button>
          <el-button size="mini" @click="offlineUser(scope.$index, scope.row)">下线</el-button>
          <el-button size="mini" @click="refreshCache(scope.$index, scope.row)">刷新缓存</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="this.userPageParam" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click='closeDialog("edit")'>
      <el-form label-width="80px" ref="editForm" :model="editForm">
        <el-form-item label="用户编码" prop="userCode">
          <el-input size="small" v-model="editForm.userCode" auto-complete="off" placeholder="请输入用户编码"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input size="small" v-model="editForm.userName" auto-complete="off" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input size="small" v-model="editForm.nickName" auto-complete="off" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input size="small" v-model="editForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮件" prop="email">
          <el-input size="small" v-model="editForm.email" placeholder="请输入邮箱地址"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存
        </el-button>
      </div>
    </el-dialog>
    <!-- 数据权限 -->
    <el-dialog title="数据权限" :visible.sync="dataAccessShow" width="30%" @click='closeDialog("perm")'>
      <el-tree ref="tree" default-expand-all="" :data="UserDept" :props="defaultProps" :default-checked-keys="checkMenu"
               node-key="id" show-checkbox>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("perm")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="menuPermSave">保存</el-button>
      </div>
    </el-dialog>
    <!-- 所属部门 -->
    <el-dialog title="所属单位" :visible.sync="deptAccessShow" width="30%" @click='closeDialog("unit")'>
      <el-tree ref="tree" default-expand-all="" :data="UserDept" :props="defaultProps" @check-change="handleClick"
               :default-checked-keys="checkMenu" node-key="id" show-checkbox check-strictly>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("unit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="unitPermSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  UserDeptTree,
  UserDeptSave,
  UserDeptdeptTree,
  UserChangeDept
} from '../../api/userMG'
import Pagination from '../../components/Pagination'
import {getRequest, postRequest} from '../../utils/api'
// import {formatRoutes} from '../../utils/menus'

export default {
  data () {
    return {
      loading: false, // 是显示加载
      title: '添加用户',
      editFormVisible: false, // 控制编辑页面显示与隐藏
      dataAccessShow: false, // 控制数据权限显示与隐藏
      deptAccessShow: false, // 控制所属单位隐藏与显示
      editForm: {
        id: '',
        userName: '',
        nickName: '',
        phone: '',
        email: ''
      },
      deptParam: {
        userIds: '',
        deptId: '',
        deptName: ''
      },
      rules: {
        userCode: [
          {required: true, message: '请输入用户编码', trigger: 'blur'}
        ],
        userName: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ],
        nickName: [
          {required: true, message: '请输入昵称', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {
            pattern: /^1(3\d|47|5((?!4)\d)|7(0|1|[6-8])|8\d)\d{8,8}$/,
            required: true,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {
            pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            required: true,
            message: '请输入正确的邮箱',
            trigger: 'blur'
          }
        ]
      },
      selectData: {
        ids: '',
        token: localStorage.getItem('loginToken')
      },
      // 重置密码
      resetPwdInfo: {
        id: '',
        token: localStorage.getItem('loginToken')
      },
      offline: {
        token: localStorage.getItem('loginToken')
      },
      userPageParam: {
        pageNum: 1,
        pageSize: 10,
        userName: '',
        userCode: '',
        status: '',
        phone: ''
      },
      userPageList: [],
      UserDept: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      checkMenu: [],
      saveRoleId: '',
      pageParam: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      }
    }
  },
  // 注册组件
  components: {
    Pagination
  },

  /**
   * 数据发生改变
   */
  watch: {},

  /**
   * 创建完毕
   */
  created () {
    this.getData(this.userPageParam)
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    getData (parameter) {
      this.loading = true
      getRequest('/system/user/page', parameter).then(resp => {
        this.loading = false
        if (resp && resp.code === 0 && resp.data) {
          this.userPageList = resp.data.records
          this.pageParam.currentPage = this.userPageParam.pageNum
          this.pageParam.pageSize = this.userPageParam.pageSize
          this.pageParam.total = resp.data.total
        }
      })
    },
    callFather (param) {
      this.userPageParam.pageNum = param.pageNum
      this.userPageParam.pageSize = param.pageSize
      this.getData(this.userPageParam)
    },
    search () {
      this.getData(this.userPageParam)
    },
    // 修改用户状态
    updateUserLockStatus: function (index, row) {
      this.loading = true
      let param = {
        id: '',
        isLock: '',
        token: localStorage.getItem('loginToken')
      }
      param.id = row.id
      let lock = row.isLock
      if (lock === 'N') {
        param.lock = 'Y'
      } else {
        param.lock = 'N'
      }
      // 修改状态
      postRequest('/system/user/updateLockStatus', this.param).then(resp => {
        this.loading = false
        if (resp && resp.code === 0 && resp.data) {
          this.$message({
            type: 'success',
            message: '状态修改成功'
          })
          this.getData(this.userPageParam)
        } else {
          this.$message({
            type: 'info',
            message: resp.msg
          })
        }
      })
    },
    handleEdit: function (index, row) {
      this.editFormVisible = true
      if (row !== undefined && row !== 'undefined') {
        this.title = '修改用户'
        this.editForm.id = row.id
        this.editForm.userCode = row.userCode
        this.editForm.userName = row.userName
        this.editForm.nickName = row.nickName
        this.editForm.phone = row.phone
        this.editForm.email = row.email
      } else {
        this.title = '添加用户'
        this.editForm.id = ''
        this.editForm.userCode = ''
        this.editForm.userName = ''
        this.editForm.nickName = ''
        this.editForm.phone = ''
        this.editForm.email = ''
      }
    },
    // 编辑、添加提交方法
    submitForm (editData) {
      this.$refs[editData].validate(valid => {
        if (valid) {
          postRequest('/system/user/save', this.editForm).then(resp => {
            this.editFormVisible = false
            this.loading = false
            if (resp && resp.code === 0 && resp.data) {
              this.getData(this.userPageParam)
              this.$message({
                type: 'success',
                message: '数据保存成功！'
              })
            } else {
              this.$message({
                type: 'info',
                message: resp.msg
              })
            }
          }).catch(err => {
            console.log(err)
            this.editFormVisible = false
            this.loading = false
            this.$message.error('保存失败，请稍后再试！')
          })
        } else {
          return false
        }
      })
    },
    // 显示部门设置
    handleDept: function (index, row) {
      this.deptAccessShow = true
      let params = 0
      UserDeptdeptTree(params)
        .then(res => {
          if (res.data.success) {
            this.UserDept = this.changeArr(res.data.data)
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        })
        .catch(err => {
          console.log(err)
          this.loading = false
          this.$message.error('配置权限失败,请稍后再试！')
        })
    },
    handleClick (data, checked, node) {
      if (checked) {
        this.$refs.tree.setCheckedNodes([])
        this.$refs.tree.setCheckedNodes([data])
        this.deptParam.deptId = data.id
        this.deptParam.deptName = data.name
      } else {
      }
    },
    // 保存部门
    unitPermSave () {
      let len = this.selectData
      let ids = []
      if (len !== 0) {
        for (let i = 0; i < len.length; i++) {
          ids.push(len[i].userId)
        }
      }
      this.deptParam.userIds = ids.join(',')
      UserChangeDept(this.deptParam)
        .then(res => {
          this.deptAccessShow = false
          if (res.success) {
            this.$message({
              type: 'success',
              message: '部门设置成功！'
            })
            this.getData(this.userPageParam)
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        })
        .catch(err => {
          console.log(err)
          this.loading = false
          this.$message.error('部门设置失败,请稍后再试！')
        })
    },
    // 选择复选框事件
    selectChange (val) {
      this.selectData = val
    },
    // 关闭编辑、增加弹出框
    closeDialog (dialog) {
      if (dialog === 'edit') {
        this.editFormVisible = false
      } else if (dialog === 'permission') {
        this.dataAccessShow = false
      } else if (dialog === 'dept') {
        this.deptAccessShow = false
      }
    },
    // 删除用户
    deleteUser (index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let deleteParam = {'id': row.id}
        postRequest('/system/user/delete', deleteParam).then(resp => {
          if (resp && resp.code === 0 && resp.data) {
            this.$message({
              type: 'success',
              message: '数据已删除!'
            })
            this.getData(this.userPageParam)
          } else {
            this.$message({
              type: 'info',
              message: resp.msg
            })
          }
        }).catch(err => {
          console.log(err)
          this.loading = false
          this.$message.error('数据删除失败，请稍后再试！')
        })
      })
    },
    // 重置密码
    resetPassword (index, row) {
      this.resetPwdInfo.id = row.id
      this.$confirm('确定要重置密码吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        postRequest('/system/user/resetPassword', this.resetPwdInfo).then(resp => {
          if (resp && resp.code === 0 && resp.data) {
            this.$message({
              type: 'success',
              message: '重置密码成功！'
            })
            this.getData(this.userPageParam)
          } else {
            this.$message({
              type: 'info',
              message: resp.msg
            })
          }
        }).catch(err => {
          console.log(err)
          this.loading = false
          this.$message.error('重置密码失败，请稍后再试！')
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消重置密码！'
          })
        })
      })
    },
    // 数据权限
    dataAccess: function (index, row) {
      this.dataAccessShow = true
      this.saveroleId = row.userId
      UserDeptTree(row.userId)
        .then(res => {
          if (res.data.success) {
            this.checkMenu = this.changeMenu(res.data.data)
            this.UserDept = this.changeArr(res.data.data)
          } else {
            this.$message({
              type: 'info',
              message: res.data.msg
            })
          }
        })
        .catch(err => {
          console.log(err)
          this.loading = false
          this.$message.error('获取权限失败，请稍后再试！')
        })
    },
    changeArr (data) {
      let pos = {}
      let tree = []
      let i = 0
      while (data.length !== 0) {
        if (data[i].pId === 0) {
          tree.push({
            id: data[i].id,
            name: data[i].name,
            pId: data[i].pId,
            open: data[i].open,
            checked: data[i].checked,
            children: []
          })
          pos[data[i].id] = [tree.length - 1]
          data.splice(i, 1)
          i--
        } else {
          let posArr = pos[data[i].pId]
          if (posArr !== undefined) {
            let obj = tree[posArr[0]]
            for (let j = 1; j < posArr.length; j++) {
              obj = obj.children[posArr[j]]
            }

            obj.children.push({
              id: data[i].id,
              name: data[i].name,
              pId: data[i].pId,
              open: data[i].open,
              checked: data[i].checked,
              children: []
            })
            pos[data[i].id] = posArr.concat([obj.children.length - 1])
            data.splice(i, 1)
            i--
          }
        }
        i++
        if (i > data.length - 1) {
          i = 0
        }
      }
      return tree
    },
    // 选中菜单
    changeMenu (arr) {
      let change = []
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].checked) {
          change.push(arr[i].id)
        }
      }
      return change
    },
    // 菜单权限-保存
    menuPermSave () {
      let param = {
        userId: this.saveRoleId,
        deptIds: ''
      }
      let node = this.$refs.tree.getCheckedNodes()
      let moduleIds = []
      if (node.length !== 0) {
        for (let i = 0; i < node.length; i++) {
          moduleIds.push(node[i].id)
        }
        param.deptIds = JSON.stringify(moduleIds)
      }
      UserDeptSave(param)
        .then(res => {
          if (res.success) {
            this.$message({
              type: 'success',
              message: '权限保存成功'
            })
            this.dataAccessShow = false
            this.getData(this.userPageParam)
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        })
        .catch(err => {
          console.log(err)
          this.loading = false
          this.$message.error('权限保存失败，请稍后再试！')
        })
    },
    // 下线用户
    offlineUser (index, row) {
      this.$confirm('确定要让' + row.userName + '用户下线吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let resetPasswordParam = {'id': row.id}
        postRequest('/system/user/offlineUser', resetPasswordParam).then(resp => {
          if (resp && resp.code === 0 && resp.data) {
            this.$message({
              type: 'success',
              message: '用户' + row.userName + '强制下线成功！'
            })
            this.getData(this.userPageParam)
          } else {
            this.$message({
              type: 'info',
              message: resp.msg
            })
          }
        }).catch(err => {
          console.log(err)
          this.loading = false
          this.$message.error('用户下线失败，请稍后再试！')
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      })
    },
    // 刷新缓存
    refreshCache (index, row) {
      postRequest('/system/user/refreshCache', this.resetPwdInfo).then(resp => {
        if (resp && resp.code === 0 && resp.data) {
          this.$message({
            type: 'success',
            message: '刷新成功！'
          })
          this.getData(this.userPageParam)
        } else {
          this.$message({
            type: 'info',
            message: resp.msg
          })
        }
      }).catch(err => {
        console.log(err)
        this.loading = false
        this.$message.error('刷新失败，请稍后再试！')
      })
    }
  }
}
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
    text-align: left;
  }

  .userRole {
    width: 100%;
  }
</style>
